package com.wjm.util;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * json鏁版嵁杞崲甯姪绫�
 * @author Mr.zhang
 *
 */
public class JsonUtil {

	/**
	 * 鑷畾涔夋椂闂存牸寮�
	 */
	private static SimpleDateFormat format;
	/**
	 * ObjectMapper瀵硅薄
	 */
	private static ObjectMapper objectMapper;

	/**
	 * 鍒濆鍖�
	 */
	static {
		format = new SimpleDateFormat(StringUtil.TIME_FORMAT);
		objectMapper = new ObjectMapper();
		objectMapper.setDateFormat(format);
	}

	/**
	 * 灏唎bj瀵硅薄杞寲鎴恓son
	 * 
	 * @param obj
	 *            瀵硅薄
	 * @return 杩斿洖json
	 */
	public static String getJson(Object obj) {
	
		
		String json = null;
		try {
			json = objectMapper.writeValueAsString(obj);
		} catch (Exception e) {
			json = null;
			e.printStackTrace();
		}
		return json;
	}

	

	/**
	 * 灏唈son杞寲鎴愬搴旂殑绫诲璞�
	 * 
	 * @param json
	 *            json瀛楃涓�
	 * @param clazz
	 *            瑕佽浆鍖栨垚鐨勭被鍨�
	 * @return 杩斿洖鐨勫璞�
	 */
	public static Object getObject(String json, Class<?> clazz) {
		Object obj = null;
		try {
			obj = objectMapper.readValue(json, clazz);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}
	
	/**
	 * 鏍规嵁key 鑾峰彇value 瀛楃涓诧紝濡傛灉鏄暟缁勶紝鍒欎細鐢紝鍒嗗壊
	 * @param json 
	 * @param key 
	 * @return value
	 */
	public static String getValue(String json,String key){
		String value = "";
		JsonParser jsonParser;
		try{
			jsonParser = objectMapper.getFactory().createParser(json);
			while(jsonParser.nextToken() != null){
				if(jsonParser.getText().equals(key) && jsonParser.nextToken() != null && jsonParser.getCurrentToken() != JsonToken.START_OBJECT){
					if(jsonParser.getCurrentToken() == JsonToken.START_ARRAY){
						while(jsonParser.nextToken() != JsonToken.END_ARRAY){
							value = value + jsonParser.getText() + ",";
						}
					}else {
						value = jsonParser.getText();
					}
					break;
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return value;
	}

	/**
	 * 鑾峰彇List<object> 浣嗘槸object瀵硅薄涓彧鍖呭惈鍩烘湰鏁版嵁
	 * 
	 * @param json
	 *            json鏁版嵁
	 * @param clazz
	 *            绫�
	 * @return 杩斿洖list<object>
	 */
	public static List<Object> getList(String json, Class<?> clazz) {
		List<Object> list = null;
		JavaType javaType = null;
		try {
			javaType = objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, clazz);
			list = objectMapper.readValue(json, javaType);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
}
